package cn.jaye.fabric.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;


/**
 *<p>Title: DruidDataSourceConfig.java</p>
 *<p>Description: 数据源属性配置</p>
 *<p>CreateDate: 2017年5月18日</p>
 *@author shen
 *@version v1.0
 */
@Configuration
@Primary //在同样的DataSource中，首先使用被标注的DataSource
public class DruidConfig extends DataSourceProperties {

    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Value("${custom.datasource.url}")
    private String dbUrl;

    @Value("${custom.datasource.username}")
    private String username;

    @Value("${custom.datasource.password}")
    private String password;

    @Value("${custom.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${custom.datasource.initialSize}")
    private int initialSize;

    @Value("${custom.datasource.minIdle}")
    private int minIdle;

    @Value("${custom.datasource.maxActive}")
    private int maxActive;

    @Value("${custom.datasource.maxWait}")
    private int maxWait;

    @Value("${custom.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${custom.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${custom.datasource.validationQuery}")
    private String validationQuery;

    @Value("${custom.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${custom.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${custom.datasource.testOnReturn}")
    private boolean testOnReturn;


    @Bean     //声明其为Bean实例
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);

        return datasource;
    }
}